package br.com.dimension.imap2rest.resources;

import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;

import org.restlet.Context;
import org.restlet.Filter;
import org.restlet.data.ChallengeRequest;
import org.restlet.data.ChallengeScheme;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Status;

import br.com.dimension.imap2rest.Imap2RestManager;
import br.com.dimension.imap2rest.holders.ClientSession;

import com.noelios.restlet.util.Base64;

public class FilterAuth extends Filter{
	
	String username = null;
	String password = null;
	String host = "imap.gmail.com";
	
	public FilterAuth(Context context){
		super(context);
	}
	private boolean sessionCheck(Request request){
		Imap2RestManager manager = Imap2RestManager.getInstance();
		Session session = null;
		Store store = null;
		ClientSession cs = null;
	
		//find a session for this user
		cs = manager.findSession(host,username,password);
		
		if(cs == null){
			session = manager.newSession();
			try {
				store = manager.getStore(session);
			} catch (NoSuchProviderException e) {
				e.printStackTrace();
				return false;
			}	
			cs = new ClientSession(session,store,host,username,password);
			manager.addSession(cs);
		}else{
			session = cs.getSession();
			store = cs.getStore();
		}
		
			if(store.isConnected() == false){
				System.out.println("Connecting to "+cs.getHostname());
				try {
					store.connect(host, username, password);
				} catch (MessagingException e) {
					e.printStackTrace();
					return false;
				}
			}
			
			request.getAttributes().put("client", cs);

	return true;		
	}
	protected void doHandle(Request request, Response response) {
	
		if(request.getChallengeResponse() == null){
			  response.setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);

		        response.setChallengeRequest(new ChallengeRequest(ChallengeScheme.HTTP_BASIC,
		                "imap2rest"));
		        return;	
		}

		username = request.getChallengeResponse().getIdentifier();
		password = new String(request.getChallengeResponse().getSecret());
		
		// assign a session to this user, or create a new one
		if(sessionCheck(request)==true){
			super.doHandle(request,response);
		}else{
			  response.setStatus(Status.CLIENT_ERROR_FORBIDDEN);
		}
	}
}
